package com.impress.commons.exception.util;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;

import com.impress.commons.exception.BaseErrorCodes;
import com.impress.commons.exception.CustomValidateException;
/**
 * 
 * @author Liutao
 * @since 2016年7月18日
 */
public class CustomValidateUtil {
	private static Validator validator =  Validation.buildDefaultValidatorFactory().getValidator();

	/**
	 * 校验整个obj参数
	 * @param obj
	 */
	public static <T> void validateEntity(T obj){
		Set<ConstraintViolation<T>> set = validator.validate(obj,Default.class);
		if(null!=set&&set.size()>0){
			String validDetailMsg="";
			for(ConstraintViolation<T> cv : set){
				validDetailMsg += cv.getPropertyPath().toString()+cv.getMessage()+"\n";
			}
			throw new CustomValidateException(BaseErrorCodes.ARG_VALID_NOT_PASS.getMessage(),validDetailMsg);
		}
	}

	/**
	 * 校验obj中属性
	 * @param obj
	 * @param propertyName
	 */
	public static <T> void validateProperty(T obj,String propertyName){
		Set<ConstraintViolation<T>> set = validator.validateProperty(obj,propertyName,Default.class);
		if(null!=set&&set.size()>0){
			String validDetailMsg="";
			for(ConstraintViolation<T> cv : set){
				validDetailMsg += cv.getPropertyPath().toString()+cv.getMessage()+"\n";
			}
			throw new CustomValidateException(BaseErrorCodes.ARG_VALID_NOT_PASS.getMessage(),validDetailMsg);
		}
	}
}
